/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.support;

import org.springframework.core.env.Environment;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;

/**
 * 环境配置读取辅助类
 * @author zpy
 * @version 1.0.0
 */
public final class PropertyReaderHelper {
    private PropertyReaderHelper() {
    }

    public static List<String> get(final Environment env, final String propName) {
        final List<String> list = new ArrayList<>();
        final String singleProp = env.getProperty(propName);
        if (Objects.nonNull(singleProp)) {
            list.add(singleProp);
            return list;
        }
        int counter = 0;
        String prop = env.getProperty(propName + "[" + counter + "]");
        while (prop != null) {
            list.add(prop);
            counter++;
            prop = env.getProperty(propName + "[" + counter + "]");
        }
        return list;
    }

    public static <T> void setIfPresent(final Environment env, final String key, final Class<T> type,
                                        final Consumer<T> function) {
        final T value = env.getProperty(key, type);
        if (value != null) {
            function.accept(value);
        }
    }

    public static String determineFilePathFromPackageName(final Class<?> clazz) {
        return "/" + clazz.getPackage().getName().replace('.', '/') + "/";
    }
}